package com.higgins.law.server;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Section;

public class MSWordService {
	public java.io.File updateMSWordFile(InputStream inputStream, String lawFirm, String address, String contact)	{
		String filenameOut = "Hello New.doc";
		
	    try
	    {
	      HWPFDocument doc = new HWPFDocument(inputStream);
	      Range range = doc.getRange();
	      Range r1 = doc.getRange(); 
	      
	      System.out.println(r1.numSections());
	      
	      for ( int i = 0; i < r1.numSections(); ++i ) { 
	    	  Section s = r1.getSection(i); 
	    	  for (int x = 0; x < s.numParagraphs(); x++)   { 
		    	  Paragraph p = s.getParagraph(x); 
		    	  for (int z = 0; z < p.numCharacterRuns(); z++)	{ 
		    		  CharacterRun run = p.getCharacterRun(z);
		    		  String text = run.text(); 
		    		  System.out.println(text);
		    		  
		    		  if (text.contains("{Lawfirm}"))
			    		  run.replaceText("{Lawfirm}", lawFirm);
		    		  if (text.contains("{Address}"))
			    		  run.replaceText("{Address}", address);
		    		  if (text.contains("{Contact}"))
			    		  run.replaceText("{Contact}", contact);
		    		  
		    		  
		    	  }
	    	  }
	      }
	      OutputStream out = new FileOutputStream(filenameOut);
	      doc.write(out);

	      out.flush();
	      out.close();
	      
	    } catch (Exception e)	{
	    	System.out.println(e.toString());
	    }
	    return new java.io.File(filenameOut);
	}
}
